<?php

namespace App\Http\Controllers;

use DB;
use Illuminate\Http\Request;
use EasyWeChat\Foundation\Application;

use App\Http\Models\User;
use App\Http\Models\Order;
use App\Http\Models\Object;
use App\Http\Models\Record;
use App\Http\Models\Captcha;
use App\Http\Models\PayRequest;
use App\Http\Models\WithdrawRequest;
use App\Http\Models\Feedback;
use App\Http\Models\Announce;

class ApplicationController extends Controller {
    public function __construct(){
  
      $user = '{"id":"oJqIl1RD9fiEHJpsxC7eMRuMTTGM"}';
      $user = json_decode($user);
      session(['wechat.oauth_user'=>$user]);

//      $res = User::where('id','1')->first();
//      var_dump($res);exit;

    }
    public function home(Application $wechat) {
        $user = session('wechat.oauth_user');
        $user = User::where('id_wechat', $user->id)->first();


        if (empty($user) || $user->body_phone == 0) {
            //return redirect('/account/bind');
            return redirect('/account/stepone');//改成三步走了
        }

        return redirect('/objects');

    }

    public function objects() {
        $user = session('wechat.oauth_user');
        $user = User::where('id_wechat', $user->id)->first();
        if($user->is_disabled > 0) return $this->denialUser();

        $objects = Object::where('is_disabled', '0')->orderBy('body_rank', 'desc')->get();

        return view('apps.objects', [
            'navigator' => 'objects',
            'controller' => 'objectsController',
            'user' => $user,
            'objects' => $objects
        ]);

    }

    public function objectsDetail($id, $period) {

        $user = session('wechat.oauth_user');
        $user = User::where('id_wechat', $user->id)->first();

        if($user->is_disabled > 0) return $this->denialUser();

        $object = Object::find($id);

        return view('apps.objectsDetail', [
            'navigator' => 'objects',
            'controller' => 'objectsDetailController',
            'user' => $user,
            'item' => $object,
            'period' => $period
        ]);

    }

    public function ordersHold() {

        $user = session('wechat.oauth_user');
        $user = User::where('id_wechat', $user->id)->first();

        if($user->is_disabled > 0) return $this->denialUser();

        $orders = Order::orderBy('created_at', 'desc')->where('id_user', $user->id)->where('striked_at', '0000-00-00 00:00:00')->get();

		$currenttime = time();
        return view('apps.ordersHold', [
            'navigator' => 'ordersHold',
            'controller' => 'ordersHoldController',
            'user' => $user,
            'orders' => $orders
        ]);

    }

    public function ordersHistory() {

        $user = session('wechat.oauth_user');
        $user = User::where('id_wechat', $user->id)->first();

        if($user->is_disabled > 0) return $this->denialUser();

        $orders = Order::orderBy('created_at', 'desc')->where('id_user', $user->id)->where('striked_at', '<>' ,'0000-00-00 00:00:00')->paginate(20);

        return view('apps.ordersHistory', [
            'navigator' => 'ordersHistory',
            'controller' => 'ordersHistoryController',
            'user' => $user,
            'orders' => $orders
        ]);

    }

    public function ordersDetail($id) {
        
        $user = session('wechat.oauth_user');
        $user = User::where('id_wechat', $user->id)->first();

        if($user->is_disabled > 0) return $this->denialUser();
        
        $item = Order::find($id);

        return view('apps.ordersDetail', [
            'navigator' => 'ordersHistory',
            'user' => $user,
            'item' => $item
        ]);

    }

   
    public function contract(){
        return view("application.contract");
    }

    /**
     * 注册第一步
     */
    public function stepone(){
        return view("application.stepone");
    }

    public function account(Application $wechat) {

        $user = session('wechat.oauth_user');
        $user = User::where('id_wechat', $user->id)->first();

        if($user->is_disabled > 0) return $this->denialUser();

        $count_refers = User::where('id_introducer', $user->id)->count();

        $count_bonus = 0;
        $records = Record::where('id_user', $user->id)->where('id_refer', '>', 0)->where('body_direction',1)->get();
        foreach ($records as $record) {
            $count_bonus = $count_bonus + $record->body_stake;
        }
        if($user->introduce_num >= 50){
            $downRecords = Record::where('id_user',$user->id)->where('id_refer','>',0)->where('body_direction',0)->get();
            $down_bonus = 0;
            foreach($downRecords as $dRecord){
                $down_bonus = $down_bonus + $dRecord->body_stake;
            }
            $count_bonus = $count_bonus - $down_bonus;
        }

        return view('application.account', [
            'title' => '会员中心',
            'user' => $user,
            'count_refers' => $count_refers,
            'count_bonus' => number_format($count_bonus, 2)
        ]);

    }


    public function inviteqrcode(){
        $user = session('wechat.oauth_user');
        $user = User::where('id_wechat',$user->id)->first();

        return view('application.inviteqrcode',[
            'user'=>$user,
            'title'=>'分享二维码',
        ]);
    }

    public function myinvites()
    {
        $user = session('wechat.oauth_user');
        $user = User::where('id_wechat',$user->id)->first();
        $myInvites = User::where('id_introducer',$user->id)->get();

        return view("application.myinvites",['items'=>$myInvites,'title'=>'我的邀请']);
    }

    public function myBusiness()
    {
        $user = session('wechat.oauth_user');
        $user = User::where('id_wechat',$user->id)->first();

        $myMembers = User::where('id_introducer',$user->id)->get();

        return view("application.myBusiness",['items'=>$myMembers,'title'=>'我的会员交易']);

    }

    public function accountBind(Request $request, Application $wechat) {

        $user = session('wechat.oauth_user');
        $user = User::where('id_wechat', $user->id)->first();


       if(!empty($user) && $user->body_phone != 0){


            return redirect('/');
        }

        if ($request->isMethod('post')) {
            if(!$request->input('mobile', null) ){
                return view('application.info', [
                    'title' => '绑定失败',
                    'icon' => 'warn',
                    'content' => '请将表单填写完整，谢谢'
                ]);
            }


            if(!$request->input('real_name', null) ){
                return view('application.info', [
                    'title' => '绑定失败',
                    'icon' => 'warn',
                    'content' => '请将表单填写完整，谢谢'
                ]);
            }

            if(Captcha::where('body_mobile', $request->input('mobile'))->where('body_code', $request->input('vcode'))->count() == 0){
                return view('application.info', [
                    'title' => '绑定失败',
                    'icon' => 'warn',
                    'content' => '您填写的验证码不正确'
                ]);
            }

            Captcha::where('body_mobile', $request->input('mobile'))->where('body_code', $request->input('vcode'))->delete();

            if(empty($user)){
                $user = new User;
                $user->id_wechat = session('wechat.oauth_user')->id;
            }

            $user->body_phone = $request->input('mobile');
            $user->real_name = $request->input('real_name');
            if($request->input('agent_id')){
                $user->id_introducer =  $request->input('agent_id');
            }

            $user->save();

            $introducer = User::where('id',$user->id_introducer)->first();
            if($introducer){
                $introducer -> introduce_num = User::where('id_introducer',$introducer->id)->count();
                $introducer ->save();
            }

            return redirect('/');
            
        } else {
            $agent_id = 0;
            if($request->input('agent_id')){
                $agent_id = $request->input('agent_id');
            }
            return view('application.accountBind', [
                'title' => '账户激活',
                'agent_id'=>$agent_id
            ]);

        }

    }



    public function accountPay(Request $request, Application $wechat) {

        $user = session('wechat.oauth_user');
        $user = User::where('id_wechat', $user->id)->first();

        if($user->is_disabled > 0) return $this->denialUser();

        if ($request->isMethod('post')) {

            
            if(!$request->input('stake', null)){
                return view('application.info', [
                    'title' => '支付失敗',
                    'icon' => 'warn',
                    'content' => '参数提交不全'
                ]);
            }

            $payRequest = new PayRequest;
            $payRequest->id_user = $user->id;
            $payRequest->body_stake = $request->input('stake');
            $payRequest->body_gateway = 'online';
            $payRequest->order_id = "CJ".time().time();


            $payRequest->save();


            $parameterForRequest = '';
            $parameterForSign = '';
            $parameters = array(
                'ORDER_ID' => $payRequest->order_id,
                'ORDER_AMT' =>$payRequest->body_stake.".00",
                'ORDER_TIME' => date('YmdHis'),
                'PAY_TYPE' => "13",
                'USER_TYPE' => "02",
                'USER_ID' => "990521000021000",
                'BUS_CODE' => '3101');
            $parameters['ADD1'] = $payRequest->id;
            $parameters['ADD2'] = $payRequest->id;
            $parameters['ADD5'] = "cesi";
            $parameters['GOODS_NAME'] = "CNY钱包";
            $parameters['GOODS_DESC'] = "CNY钱包";


            
           //print_r($parameters);exit();
            ksort($parameters);
            reset($parameters);
            $parameterForSign = $parameters["ORDER_ID"].$parameters["ORDER_AMT"].$parameters["ORDER_TIME"].$parameters["PAY_TYPE"].$parameters["USER_TYPE"].$parameters["USER_ID"].$parameters["BUS_CODE"];

            /*
            foreach ($parameters as $key => $value) {
                $parameterForSign = $parameterForSign  . $value ;
            }*/

            $sign = strtoupper(substr(MD5(strtoupper(MD5($parameterForSign))."11CC09E7CFDC4CEF56CC09E7CFDC4C00"),8,16)); //strtoupper(md5($parameterForSign . 'key=' . "0123456789ABCDEF0123456789ABCDEF"));
            $parameters['SIGN'] =$sign;// "EBA20022222AAC31";//$sign;
            $parameters["CCT"] = "CNY";

            $parameters["SIGN_TYPE"] = "03";
            $parameters["BG_URL"] = env('PAYMENT_URL_NO');
            $parameters["PAGE_URL"] = env('PAYMENT_URL_RE');



            
            $requestURL = 'http://nps.api.yiyoupay.net/YiYouQuickPay/controller/pay?ORDER_ID='.$parameters['ORDER_ID'].'&ORDER_AMT='.$parameters['ORDER_AMT'].'&ORDER_TIME='.$parameters['ORDER_TIME'].'&PAY_TYPE='.$parameters['PAY_TYPE'].'&USER_TYPE='.$parameters['USER_TYPE'].'&USER_ID='.$parameters['USER_ID'].'&BUS_CODE='.$parameters['BUS_CODE'].'&GOODS_NAME='.$parameters['GOODS_NAME'].'&GOODS_DESC='.$parameters['GOODS_DESC'].'&SIGN='.$parameters['SIGN'].'&CCT='.$parameters['CCT'].'&SIGN_TYPE='.$parameters['SIGN_TYPE'].'&BG_URL='.$parameters['BG_URL'].'&PAGE_URL='.$parameters['PAGE_URL'];


            $ch = curl_init();

            curl_setopt($ch, CURLOPT_URL, $requestURL);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_TIMEOUT,300);
            // post数据
            curl_setopt($ch, CURLOPT_POST, 1);
            // post的变量
            curl_setopt($ch, CURLOPT_POSTFIELDS, array());

            $output = curl_exec($ch);
            curl_close($ch);

            //打印获得的数据

            $p = xml_parser_create();
            xml_parse_into_struct($p, $output, $vals, $index);
            xml_parser_free($p);


            return view('application.accountPayRedirect', [
                'requestURL' => $requestURL,
                'parameters' => $parameters,
                'sign' => $sign,
                'wxurl'=>$vals[23]["value"]
            ]);

        }

        return view('application.accountPay', [
            'title' => '我要充值'
        ]);
    }

    public function accountPayStaff(Application $wechat) {
        return view('application.accountPayStaff', [
            'title' => '人工充值'
        ]);
    }

    public function accountPayNew(Request $request){

//return  $this->accountPayNewSure($request);
/*        $user = session('wechat.oauth_user');
        $user = User::where('id_wechat', $user->id)->first();

        $pay_orderid = date('YmdHis',time()).rand(100,999);
        $ip = $request->getClientIp();
        $sub_openid = $user->id_wechat;

        $payRequest = new PayRequest;
        $payRequest->id_user = $user->id;
        $payRequest->body_stake = 0;//we don't know how much at this time
        $payRequest->body_gateway = 'online';
        $payRequest->order_id = $pay_orderid;
        $payRequest->save();
*/

        return view("application.accountPayNew",["title"=>'在线充值']);
         
//          return view("application.accountPayceshi",['title'=>]);
    }

    public function accountPayNewSure(Request $request){
           $amount = $request -> input('amount');
           $way = $request->input('way');
           if($way == 'weixin'){
	      $businessCode = 'WXPAYWEBT1';
              $wxuser = session('wechat.oauth_user');
              $openId = $wxuser->id;
           }else{
              $businessCode = 'WXPAYF2FT1';
           }
           //$amount = 1;
           $merchantGenCode = date('YmdHis',time()).rand(100,999);
           $callBackUrl="http://www.islinyi.com/api/bgRetUrl";
           $frontCallback="http://www.islinyi.com/api/retUrl";
           $operatorCode = '00007620664264';
           $merchantCode = '8216277547'; 
           
           if($way == 'weixin'){ 
           	//$post_data = ["request"=>'{"detail":[{"amount":'.$amount.',"businessCode":"'.$businessCode.'","callBackUrl":"'.$callBackUrl.'","merchantGenCode":"'.$merchantGenCode.'","openId":"'.$openId.'","operatorCode":"'.$operatorCode.'","purpose":"在线充值"}],"operatorCode":"'.$operatorCode.'","businessCode":"'.$businessCode.'","merchantCode":"'.$merchantCode.'"}']; 
           	$post_data = ["request"=>'{"detail":[{"amount":'.$amount.',"businessCode":"'.$businessCode.'","callBackUrl":"'.$callBackUrl.'","frontCallback":"'.$frontCallback.'","merchantGenCode":"'.$merchantGenCode.'","openId":"'.$openId.'","operatorCode":"'.$operatorCode.'","purpose":"在线充值"}],"operatorCode":"'.$operatorCode.'","businessCode":"'.$businessCode.'","merchantCode":"'.$merchantCode.'"}']; 
	    $requestUrl = 'http://gateway.ipaysoon.com/MSZFPlatform/wxpay/webpay'; 
	   }else{
           	$post_data = ["request"=>'{"detail":[{"amount":'.$amount.',"businessCode":"'.$businessCode.'","callBackUrl":"'.$callBackUrl.'","merchantGenCode":"'.$merchantGenCode.'","operatorCode":"'.$operatorCode.'","purpose":"在线充值"}],"operatorCode":"'.$operatorCode.'","businessCode":"'.$businessCode.'","merchantCode":"'.$merchantCode.'"}']; 
	    $requestUrl = 'http://gateway.ipaysoon.com/MSZFPlatform/alipay/qrpay'; 
            }

	    $ch = curl_init();

            curl_setopt($ch, CURLOPT_URL, $requestUrl);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_TIMEOUT,300);
            // post数据
            curl_setopt($ch, CURLOPT_POST, 1);
            // post的变量
            curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);

            $output = curl_exec($ch);
            curl_close($ch);
            $result = json_decode($output,true);
//	    var_dump($result);exit;

            $user = session('wechat.oauth_user');
            $user = User::where('id_wechat', $user->id)->first();
            $payRequest = new PayRequest;
            $payRequest->id_user = $user->id;
            $payRequest->body_stake =  $amount/100;
            $payRequest->body_gateway = 'online';
            $payRequest->order_id = $merchantGenCode;
            $payRequest->save();

            if($way == 'weixin'){
                return redirect($result['detail'][0]['url']);	
            }

            return view("application.accountPayNewSure",['title'=>'确认支付','url'=>$result['detail'][0]['url'],'amount'=>$result['detail'][0]['amount']]); 
    }

    //don't need this 
    public function accountPayNewSure1(Request $request,Application $wechat)
    {
        $bank_map = [
           'Alipayjszf'=>'ALIPAY',
           'WftWx'=>'WXZF',
           'WftGzh'=>'WXZF',
           'WftZfb'=>'alipay',
           'Gopaywap'=>'SPDB',
	   'XingYeWx'=>'WXZF',
           'XingYeZfb'=>'ALIPAY',
           'AiYiWxSm'=>'WXZF',
           'AiYiZfbSm'=>'alipay',
           'AiYiWxGzh'=>'WXZF'
        ];

        $bank_code = [
          'CMBC','ICBC','CCB','SPDB','ABC','CMSB','SDB','CIB','BCM','CEB','BOC','PAB','GDB','CNCB','NBCB'
        ];

        $tongdao = $request->input('tongdao');
        if(isset($bank_map[$tongdao])){
          $pay_bankcode=$bank_map[$tongdao];
          $_type = 'tongdao';
        }elseif(in_array($tongdao,$bank_code)){
          $pay_bankcode=$tongdao;
          $_type = 'bank';
        }
        
        $stake = $request->input('stake');
        $gateWay = $request->input('gateway');

	$pay_memberid = "11964";   //商户ID
        $pay_orderid = 'ZHJ'.date('YmdHis',time()).rand(100,999);
        $pay_amount = sprintf("%.2f",$stake);    //交易金额
//        $pay_amount="0.01";
        $pay_applydate = date("Y-m-d H:i:s");  //订单时间
        

        $pay_notifyurl="http://".env('PAY_DOMAIN')."/api/bgRetUrl";
        $pay_callbackurl="http://".env('PAY_DOMAIN')."/api/retUrl";
//        $pay_notifyurl = "http://www.zhifupingtai.com/ylyl/server.php";   //服务端返回地址
//        $pay_callbackurl = "http://www.zhifupingtai.com/ylyl/page.php";  //页面跳转返回地址
        $Md5key = "QgtlbbBxkn8wAcKR2O86rRTgsHUMnR";   //密钥
        $tjurl = "http://zf.cnzypay.com/Pay_Index.html";   //提交地址,如有变动请到官网下载最新接口文档
        $requestarray = array(
            "pay_memberid" => $pay_memberid,
            "pay_orderid" => $pay_orderid,
            "pay_amount" => $pay_amount,
            "pay_applydate" => $pay_applydate,
            "pay_bankcode" => $pay_bankcode,
            "pay_notifyurl" => $pay_notifyurl,
            "pay_callbackurl" => $pay_callbackurl
        );
        ksort($requestarray);
        reset($requestarray);
        $md5str = "";
        foreach ($requestarray as $key => $val) {
            $md5str = $md5str . $key . "=>" . $val . "&";
        }
//            echo($md5str . "key=" . $Md5key."<br /> ");
        $sign = strtoupper(md5($md5str . "key=" . $Md5key)); 
        $requestarray["pay_md5sign"] = $sign;
        if($_type == 'tongdao'){
            $requestarray['tongdao'] = $tongdao; 
        }
        
     


        $str = '<form id="Form1" name="Form1" method="post" action="'.$tjurl.'">';
        foreach ($requestarray as $key => $val) {
            $str = $str . '<input type="hidden" name="'.$key.'" value="'.$val.'">';
        }
        $str = $str . '<div style="height:30px;"></div><input type="submit" class="weui_btn weui_btn_primary" value="立刻支付">';
        $str = $str . '</form>';
//        $str = $str . '';

        $user = session('wechat.oauth_user');
        $user = User::where('id_wechat', $user->id)->first();
        if($user->is_disabled > 0) return $this->denialUser();


        $payRequest = new PayRequest;
        $payRequest->id_user = $user->id;
        $payRequest->body_stake = $pay_amount;
//        $payRequest->body_stake = '1.00';
        $payRequest->body_gateway = $gateWay;
        $payRequest->order_id = $pay_orderid; 
        $payRequest->save();

        return view("application.accountPayNewSure",[
          'str' => $str,
          'title'=>'立刻支付',
        ]);

    }

    public function accountWithdrawRecords(Application $wechat) {

        $user = session('wechat.oauth_user');
        $user = User::where('id_wechat', $user->id)->first();

        if($user->is_disabled > 0) return $this->denialUser();

        $withdrawRequests = WithdrawRequest::where('id_user', $user->id)->orderBy('created_at', 'desc')->get();

        return view('application.accountWithdrawRecords', [
            'title' => '提现记录',
            'withdrawRequests' => $withdrawRequests
        ]);

    }

    public function accountWithdraw(Request $request, Application $wechat) {

        $user = session('wechat.oauth_user');
        $user = User::where('id_wechat', $user->id)->first();

        if($user->is_disabled > 0) return $this->denialUser();

        if ($request->isMethod('post')) {

            if(!$request->input('name', null)
                || !$request->input('number', null)
                || !$request->input('bank', null)
                || !$request->input('deposit', null)
                || !$request->input('stake', null)){
                return view('application.info', [
                    'title' => '提现失败',
                    'icon' => 'warn',
                    'content' => '请将表单填写完整，謝謝'
                ]);
            }

            if(intval($request->input('stake', 0)) < 100) {
                return view('application.info', [
                    'title' => '提现失败',
                    'icon' => 'warn',
                    'content' => '单次提现金额不能低于 100 元'
                ]);
            }

            if(intval($request->input('stake', 0)) > 5000) {
                return view('application.info', [
                    'title' => '提现失败',
                    'icon' => 'warn',
                    'content' => '单次提现金额不能高于 5000 元'
                ]);
            }

            $addtime = strtotime($user->created_at);
            if( (time()-$addtime) < 86400 ){
                return view('application.info', [
                    'title' => '提现失败',
                    'icon' => 'warn',
                    'content' => '新用户必须注册满24小时以后才可提现'
                ]);
            }

            $time = time();
            $currentdate = date("Y-m-d",$time);
            $starttime = $currentdate." 10:00:00";
            $endtime = $currentdate." 14:00:00";


            if($time < strtotime($starttime)){
                return view('application.info', [
                    'title' => '提现失败',
                    'icon' => 'warn',
                    'content' => '提现时间为10点-14点'
                ]);
            }

            if($time > strtotime($endtime)){
                return view('application.info', [
                    'title' => '提现失败',
                    'icon' => 'warn',
                    'content' => '提现时间为10点-14点'
                ]);
            }

            $newstarttime = $currentdate." 00:00:00";
            $newendtime = $currentdate." 23:59:59";
            $count = WithdrawRequest::where('id_user', $user->id)->where('processed_at', '<', $newendtime)->where('created_at', '>', $currentdate)->count();

            if(intval($count) >= 2){
                return view('application.info', [
                    'title' => '提现失败',
                    'icon' => 'warn',
                    'content' => '每个用户每天只能提现两次'
                ]);
            }



            if(intval($request->input('stake', 0)) > 5000) {
                return view('application.info', [
                    'title' => '提现失败',
                    'icon' => 'warn',
                    'content' => '单次提现金额不能高于 5000 元'
                ]);
            }

            $currentdate = date("Y-m-d",$time);
            $starttime = $currentdate." 10:00:00";
            $endtime = $currentdate." 14:00:00";


            $addtime = strtotime($user->created_at);
            if( (time()-$addtime) < 86400 ){
                return view('application.info', [
                    'title' => '提现失败',
                    'icon' => 'warn',
                    'content' => '新用户必须注册满24小时以后才可提现'
                ]);
            }

            $newstarttime = $currentdate." 00:00:00";
            $newendtime = $currentdate." 23:59:59";
            $count = WithdrawRequest::where('id_user', $user->id)->where('processed_at', '<', $newendtime)->where('created_at', '>', $currentdate)->count();

            if(intval($count) >= 1){
                return view('application.info', [
                    'title' => '提现失败',
                    'icon' => 'warn',
                    'content' => '每个用户每天只能提现一次'
                ]);
            }



            if(intval($request->input('stake', 0)) > intval($user->body_balance)) {
                return view('application.info', [
                    'title' => '提现失败',
                    'icon' => 'warn',
                    'content' => '您当前的账户余额不足'
                ]);
            }

            if(intval($request->input('stake', 0)) % 100 != 0) {
                return view('application.info', [
                    'title' => '提现失败',
                    'icon' => 'warn',
                    'content' => '提现金额必须为 100 元的倍数'
                ]);
            }

            /*
            $orderSum = Order::where('id_user', $user->id)->sum('body_stake');
            if(intval($orderSum) < 300){
                return view('application.info', [
                    'title' => '提现失败',
                    'icon' => 'warn',
                    'content' => '为避免恶意透支，累积交易金额超过 300 元即可提现'
                ]);
            }*/

            DB::beginTransaction();

            $user->body_balance = $user->body_balance - $request->input('stake');
            $user->save();

            if($user->body_balance < 0) {
                DB::rollback();
            } else {
                $withdrawRequest = new WithdrawRequest;
                $withdrawRequest->id_user = $user->id;
                $withdrawRequest->body_stake = $request->input('stake');
                $withdrawRequest->body_name = $request->input('name');
                $withdrawRequest->body_bank = $request->input('bank');
                $withdrawRequest->body_deposit = $request->input('deposit');
                $withdrawRequest->body_number = $request->input('number');
                $withdrawRequest->save();

                $record = new Record;
                $record->id_user = $user->id;
                $record->id_withdrawRequest = $withdrawRequest->id;
                $record->body_name = '结余提现';
                $record->body_direction = 0;
                $record->body_stake = $withdrawRequest->body_stake;
                $record->save();
            }

            DB::commit();

            return view('application.info', [
                'title' => '申请成功',
                'icon' => 'success',
                'content' => '我们已收到您的提现申请，将在24小时内处理'
            ]);

        } else {
            return view('application.accountWithdraw', [
                'title' => '我要提現',
                'user' => $user
            ]);
        }

    }

    public function accountRecords(Application $wechat) {

        $user = session('wechat.oauth_user');
        $user = User::where('id_wechat', $user->id)->first();

        if($user->is_disabled > 0) return $this->denialUser();

        $records = Record::orderBy('created_at', 'desc')->where('id_user', $user->id)->paginate(20);

        return view('application.accountRecords', [
            'title' => '资金记录',
            'records' => $records
        ]);

    }

    public function accountOrders(Application $wechat) {

        $user = session('wechat.oauth_user');
        $user = User::where('id_wechat', $user->id)->first();

        if($user->is_disabled > 0) return $this->denialUser();

        $orders = Order::orderBy('created_at', 'desc')->where('id_user', $user->id)->paginate(20);

        return view('application.accountOrders', [
            'title' => '交易记录',
            'orders' => $orders
        ]);

    }

    public function accountExpand(Application $wechat, $id) {

        $qrcode = $wechat->qrcode;
        $result = $qrcode->forever($id);
        $ticket = $result->ticket;

        return view('application.accountExpand', [
            'title' => '云交易',
            'qrcode' => $qrcode->url($ticket)
        ]);

    }

    public function support(Application $wechat) {
        return view('application.support', [
            'title' => '在线咨询'
        ]);
    }

    public function supportFaq(Application $wechat) {
        return view('application.supportFaq', [
            'title' => '常见问题'
        ]);
    }

    public function supportService(Application $wechat) {
        return view('application.supportService', [
            'title' => '在线客服'
        ]);
    }

    public function supportGonggao() {
        return view('apps.gonggao', [
            'title' => '资讯公告'
        ]);
    }

    public function supportFeedback(Request $request, Application $wechat) {

        if ($request->isMethod('post')) {

            if(!$request->input('content', null)
            || !$request->input('tool', null)
            || !$request->input('number', null)){
                return view('application.info', [
                    'title' => '返回失败',
                    'icon' => 'warn',
                    'content' => '请将表单填写完整，謝謝'
                ]);
            }

            $feedback = new Feedback;
            $feedback->body_content = $request->input('content');
            $feedback->body_tool = $request->input('tool');
            $feedback->body_number = $request->input('number');
            $feedback->wechat = $request->input('wechat');
            $feedback->qq = $request->input('qq');
            $feedback->save();

            return view('application.info', [
                'title' => '反馈成功',
                'icon' => 'success',
                'content' => '我们已经收到您的反馈，谢谢'
            ]);
            
        } else {

            return view('application.supportFeedback', [
                'title' => '意见反馈'
            ]);

        }

    }


    /**
     * 公告列表
     * @return mixed
     */
    public function announce()
    {
        $datas = Announce::orderBy("created_at","desc");
        $datas = $datas->paginate(50);


        return view("application.announce",['title'=>'公告列表','datas'=>$datas]);
    }


    /**
     * 公告详情
     * @return mixed
     */
    public function announceContent($id)
    {
        $announce = Announce::find($id);

        return view("application.announceContent",['title'=>$announce->body_title,'announce'=>$announce]);
    }

}
